<template>
  <div class="homework-management">
    <div class="header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">返回主页</button>
        <h2>作业管理</h2>
      </div>
      <div class="class-filter">
        <label>班级筛选：</label>
        <select v-model="selectedClassId" @change="loadHomeworks">
          <option value="">所有班级</option>
          <option v-for="cls in classList" :key="cls.id" :value="cls.id">{{ cls.className }}</option>
        </select>
      </div>
    </div>
    
    <div class="homework-table">
      <table class="layui-table" lay-filter="homeworkTable">
        <thead>
          <tr>
            <th lay-data="{field: 'title', width: 300}">作业标题</th>
            <th lay-data="{field: 'classInfo', width: 150, templet: '#classTpl'}">所属班级</th>
            <th lay-data="{field: 'createdAt', width: 180, templet: '#timeTpl'}">发布时间</th>
            <th lay-data="{field: 'deadline', width: 180, templet: '#deadlineTpl'}">截止时间</th>
            <th lay-data="{field: 'operations', width: 200, templet: '#operationsTpl'}">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="homework in homeworks" :key="homework.id">
            <td>{{ homework.title }}</td>
            <td>{{ homework.classInfo ? homework.classInfo.className : '全年级' }}</td>
            <td>{{ formatDate(homework.createdAt) }}</td>
            <td>{{ homework.deadline ? formatDate(homework.deadline) : '无截止时间' }}</td>
            <td>
              <button class="layui-btn layui-btn-sm" @click="editHomework(homework)">编辑</button>
              <button class="layui-btn layui-btn-danger layui-btn-sm" @click="deleteHomework(homework.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 编辑作业弹窗 -->
    <div v-if="isEditModalVisible" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑作业</h3>
          <button type="button" class="modal-close" @click="closeEditModal">&times;</button>
        </div>
        <div class="modal-body">
          <form class="layui-form" lay-filter="editHomeworkForm">
            <div class="layui-form-item">
              <label class="layui-form-label">作业标题</label>
              <div class="layui-input-block">
                <input type="text" name="title" v-model="editingHomework.title" required lay-verify="required" placeholder="请输入作业标题" class="layui-input">
              </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">选择班级</label>
          <div class="layui-input-block">
            <select name="classId" v-model="editingHomework.classId">
              <option value="">全年级</option>
              <option v-for="cls in classList" :key="cls.id" :value="cls.id">{{ cls.className }}</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">截止时间</label>
          <div class="layui-input-block">
            <input type="datetime-local" name="deadline" v-model="editingHomework.deadline" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item layui-form-text">
          <label class="layui-form-label">作业内容</label>
          <div class="layui-input-block">
            <textarea name="content" v-model="editingHomework.content" required lay-verify="required" placeholder="请输入作业内容" class="layui-textarea"></textarea>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">附件</label>
          <div class="layui-input-block">
            <input type="file" name="attachment" id="homeworkAttachment" accept="image/*,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx">
            <div v-if="editingHomework.attachment" class="current-attachment">
              当前附件：<a :href="editingHomework.attachment" target="_blank">查看附件</a>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">粘贴图片</label>
          <div class="layui-input-block">
            <div v-if="editingHomework.images" class="images-preview">
              <p>已存在粘贴的图片数据</p>
              <div class="images-container">
                <img v-for="(image, index) in parseImages(editingHomework.images)" :key="index" :src="image" class="preview-image" alt="图片预览" @click="viewImage(image)">
              </div>
              <div class="image-tip">点击图片可查看原始大小，编辑内容时可以继续粘贴图片，原有图片数据会被保留</div>
            </div>
            <div v-else class="image-tip">在内容编辑框中直接粘贴图片即可添加图片</div>
          </div>
        </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveHomework">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" @click="closeEditModal">取消</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 图片查看器 -->
  <div v-if="isImageViewerVisible" class="image-viewer-overlay" @click.self="closeImageViewer">
    <div class="image-viewer-content">
      <button class="image-viewer-close" @click="closeImageViewer">&times;</button>
      <img :src="currentViewImage" :class="['image-viewer-img', { maximized: isMaximized }]" :alt="'查看图片'">
      <div class="image-viewer-footer">
        <button class="layui-btn layui-btn-sm" @click="maximizeImage">
          {{ isMaximized ? '原始大小' : '最大化' }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  width: 800px;
  max-height: 600px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-close:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

/* 原有样式保持 */
.homework-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #1e9fff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.back-btn:hover {
  background-color: #40a9ff;
}

.class-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.class-filter select {
  padding: 5px 10px;
  border: 1px solid #d0d0d0;
  border-radius: 4px;
  color: #333;
}

.homework-table {
  margin-top: 20px;
}

.layui-table {
  margin: 0;
}

.layui-layer-content {
  padding: 20px;
}
</style>

<script>
import { api } from '@/utils/api.js';

export default {
  name: 'HomeworkManagement',
  data() {
    return {
      homeworks: [],
      classList: [],
      selectedClassId: '',
      editingHomework: {
        id: null,
        title: '',
        content: '',
        classId: '',
        deadline: '',
        attachment: '',
        images: null
      },
      isEditModalVisible: false,
      isImageViewerVisible: false,
      currentViewImage: '',
      isMaximized: false
    };
  },
  mounted() {
    this.initPage();
  },
  methods: {
    // 返回主页
    goBack() {
      this.$router.push('/teacher/home');
    },
    /**
     * 初始化页面数据
     */
    async initPage() {
      await this.loadClasses();
      await this.loadHomeworks();
      this.initForm();
    },
    
    /**
     * 加载班级列表
     */
    async loadClasses() {
      try {
        const response = await api.getClasses();
        if (response && response.success) {
          // 从response.data.classes中获取班级数据，适配后端返回格式
          this.classList = response.data?.classes || response.data || [];
        }
      } catch (error) {
        console.error('加载班级失败:', error);
        layer.msg('加载班级失败', { icon: 2 });
      }
    },
    
    /**
     * 加载作业列表
     */
    async loadHomeworks() {
      try {
        const params = {};
        if (this.selectedClassId) {
          params.classId = this.selectedClassId;
        }
        const response = await api.getHomeworks(params);
        if (response && response.success) {
          this.homeworks = response.data || [];
        }
      } catch (error) {
        console.error('加载作业失败:', error);
        layer.msg('加载作业失败', { icon: 2 });
      }
    },
    
    /**
     * 编辑作业
     * @param {Object} homework - 作业对象
     */
    async editHomework(homework) {
      try {
        // 从作业列表中直接获取作业数据，避免调用不存在的API端点
        const homeworkData = this.homeworks.find(h => h.id === homework.id);
        if (homeworkData) {
          this.editingHomework = {
            id: homeworkData.id,
            title: homeworkData.title,
            content: homeworkData.content,
            classId: homeworkData.classId || '',
            deadline: homeworkData.deadline ? new Date(homeworkData.deadline).toISOString().slice(0, 16) : '',
            attachment: homeworkData.attachment,
            images: homeworkData.images
          };
          
          this.showEditModal();
        } else {
          console.error('未找到作业数据:', homework.id);
          layer.msg('未找到作业数据', { icon: 2 });
        }
      } catch (error) {
        console.error('获取作业详情失败:', error);
        layer.msg('获取作业详情失败', { icon: 2 });
      }
    },
    
    /**
     * 删除作业
     * @param {number} homeworkId - 作业ID
     */
    deleteHomework(homeworkId) {
      layer.confirm('确定要删除该作业吗？删除后将无法恢复。', {
        btn: ['确定', '取消']
      }, async (index) => {
        try {
            const response = await api.deleteAssignment(homeworkId);
            if (response && response.success) {
            layer.msg('删除成功', { icon: 1 });
            this.loadHomeworks();
          } else {
            layer.msg(response?.message || '删除失败', { icon: 2 });
          }
        } catch (error) {
          console.error('删除作业失败:', error);
          layer.msg('删除失败', { icon: 2 });
        } finally {
          layer.close(index);
        }
      });
    },
    
    /**
     * 显示编辑弹窗
     */
    showEditModal() {
      // 使用Vue的数据绑定方式控制弹窗，避免使用jQuery
      this.isEditModalVisible = true;
      this.$nextTick(() => {
        layui.form.render();
      });
    },
    
    /**
     * 关闭编辑弹窗
     */
    closeEditModal() {
      this.isEditModalVisible = false;
      this.resetEditingHomework();
    },
    
    /**
     * 初始化表单提交事件
     */
    initForm() {
      layui.form.on('submit(saveHomework)', async (data) => {
        try {
          // 我们不再需要这个FormData，因为已经在api.updateAssignment内部创建了
          
          // 获取附件文件
          let attachmentFile = null;
          const fileInput = document.getElementById('homeworkAttachment');
          if (fileInput.files && fileInput.files[0]) {
            attachmentFile = fileInput.files[0];
          }
          
          // 调用API更新作业
          const response = await api.updateAssignment(
            this.editingHomework.id,
            this.editingHomework.title,
            this.editingHomework.content,
            attachmentFile,
            this.editingHomework.classId || null,
            this.editingHomework.deadline || null,
            this.editingHomework.images || null
          );
          
          if (response && response.success) {
            layer.msg('保存成功', { icon: 1 });
            layer.close(this.currentModal);
            this.loadHomeworks();
          } else {
            layer.msg(response?.message || '保存失败', { icon: 2 });
          }
        } catch (error) {
          console.error('更新作业失败:', error);
          layer.msg('保存失败', { icon: 2 });
        }
        
        return false;
      });
    },
    
    /**
     * 重置编辑表单
     */
    resetEditingHomework() {
      this.editingHomework = {
        id: null,
        title: '',
        content: '',
        classId: '',
        deadline: '',
        attachment: '',
        images: null
      };
      document.getElementById('homeworkAttachment').value = '';
    },
    
    /**
     * 格式化日期
     * @param {string|Date} date - 日期对象或字符串
     * @returns {string} 格式化后的日期字符串
     */
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    /**
     * 解析图片数据
     * @param {string|Array} imagesData - 图片数据字符串或数组
     * @returns {Array} 图片数据URL数组
     */
    parseImages(imagesData) {
      if (!imagesData) return [];
      
      let images = [];
      
      // 尝试解析JSON字符串
      if (typeof imagesData === 'string') {
        try {
          images = JSON.parse(imagesData);
        } catch (e) {
          // 如果不是有效的JSON，直接将字符串作为单个图片路径
          images = [imagesData];
        }
      } else if (Array.isArray(imagesData)) {
        // 如果已经是数组，直接使用
        images = imagesData;
      }
      
      // 为相对路径添加完整的URL前缀
      const baseUrl = '/uploads/images/';
      return images.map(img => {
        // 如果已经是完整URL，则直接返回
        if (img.startsWith('http://') || img.startsWith('https://') || img.startsWith('/')) {
          return img;
        }
        // 否则添加基础URL前缀
        return baseUrl + img;
      });
    },
    
    /**
     * 查看图片
     * @param {string} imageUrl - 图片URL
     */
    viewImage(imageUrl) {
      this.currentViewImage = imageUrl;
      this.isImageViewerVisible = true;
      this.isMaximized = false;
      // 防止页面滚动
      document.body.style.overflow = 'hidden';
    },
    
    /**
     * 关闭图片查看器
     */
    closeImageViewer() {
      this.isImageViewerVisible = false;
      // 恢复页面滚动
      document.body.style.overflow = 'auto';
    },
    
    /**
     * 最大化/原始大小切换
     */
    maximizeImage() {
      this.isMaximized = !this.isMaximized;
    }
  }
};
</script>

<style scoped>
/* 图片查看器样式 */
.image-viewer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  padding: 20px;
}

.image-viewer-content {
  position: relative;
  max-width: 100%;
  max-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.image-viewer-close {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  font-size: 32px;
  color: white;
  cursor: pointer;
  z-index: 10;
}

.image-viewer-img {
  max-width: 100%;
  max-height: 80vh;
  transition: all 0.3s ease;
  object-fit: contain;
}

.image-viewer-img.maximized {
  max-width: 100vw;
  max-height: 100vh;
}

.image-viewer-footer {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

/* 预览图片样式优化 */
.preview-image {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.preview-image:hover {
  transform: scale(1.02);
}

.homework-management {
  padding: 20px;
}

.header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 15px;
    }
    
    .back-btn {
      background-color: #1890ff;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }
    
    .back-btn:hover {
      background-color: #40a9ff;
    }

.header h2 {
  margin: 0;
}

.class-filter {
  display: flex;
  align-items: center;
}

.class-filter label {
  margin-right: 10px;
}

.class-filter select {
  width: 200px;
}

.current-attachment {
  margin-top: 10px;
  color: #666;
}

.current-attachment a {
  color: #1E9FFF;
  text-decoration: none;
}

.current-attachment a:hover {
  text-decoration: underline;
}

.images-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.images-preview p {
  margin: 0 0 10px 0;
  color: #52c41a;
  font-weight: 500;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.preview-image {
  max-width: 200px;
  max-height: 150px;
  border-radius: 4px;
  border: 1px solid #ddd;
  object-fit: contain;
  background-color: white;
  padding: 5px;
}

.image-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>